package com.eascs.admin.o2o.loan.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import com.eascs.account.api.IFeeService;
import com.eascs.account.api.constants.enums.SourceType;
import com.eascs.account.api.constants.enums.TradeType;
import com.eascs.account.api.vo.TradeDetailVO;
import com.eascs.account.api.vo.TradeParamsVO;
import com.eascs.admin.common.utils.AccountConstants;
import com.eascs.admin.o2o.internal.entity.LoanapplyExpand;
import com.eascs.admin.o2o.internal.util.StatusContexts;
import com.eascs.admin.o2o.loan.entity.O2oLoanapplyEntity;
import com.eascs.admin.o2o.loan.entity.O2oLoanapplyExpandRecord;
import com.eascs.admin.o2o.loanAccount.entity.AccountLog;
import com.eascs.admin.o2o.loanAccount.entity.O2oLoanapplyAccountEntity;
import com.eascs.admin.o2o.loanAccount.service.IAccountLogService;
import com.eascs.admin.o2o.loanAccount.serviceimpl.O2oLoanapplyAccountImpl;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.util.StringUtil;
import com.eascs.common.util.UuidUtil;
import com.eascs.crm.common.custnew.entity.CustomerEntity;
import com.eascs.workflow.common.vo.ModelResult;

@Service
public class ChargingService {
	
	private static Logger logger = LoggerFactory.getLogger(ChargingService.class);
	
	@Reference
	private IO2oLoanapplyExpandRecordService iO2oLoanapplyExpandRecordService;
	
	@Autowired
	private O2oLoanapplyAccountImpl io2oLoanapplyAccountService;
	@Autowired
	private O2oChargeSituationService o2oChargeSituationService;
	
	@Reference
	private IFeeService iFeeService;
	
	@Reference
	private IAccountLogService iAccountLogService;
	
	@Autowired
	private O2oLoanapplyService o2oLoanapplyService;
	
	/**
	 * 扣费、退费(银行申报审节点扣费)
	 * 
	 * @param expand
	 * @param type
	 * @return
	 */
	@Transactional(transactionManager = "o2oTransactionManager")
	public String Charging(LoanapplyExpand expand, String type) {
		
		O2oLoanapplyExpandRecord expandRecord = iO2oLoanapplyExpandRecordService.queryById(expand.getId());
		if (null == expandRecord) {
			expandRecord = new O2oLoanapplyExpandRecord();
			expandRecord.setId(UuidUtil.generateShortUuid());
			expandRecord.setLoanExpandId(expand.getId());
			expandRecord.setRedDeposite(expand.getRecDeposite());
			expandRecord.setRedManager(expand.getRecManger());
			expandRecord.setRedRisk(expand.getRecRisk());
			expandRecord.setUpdateTime(new Date());
		} else if (StatusContexts.O2O_YES.equals(expandRecord.getStatus())) {
			expandRecord = new O2oLoanapplyExpandRecord();
			expandRecord.setId(UuidUtil.generateShortUuid());
			expandRecord.setLoanExpandId(expand.getId());
			expandRecord.setRedDeposite(expand.getRecDeposite());
			expandRecord.setRedManager(expand.getRecManger());
			expandRecord.setRedRisk(expand.getRecRisk());
			expandRecord.setUpdateTime(new Date());
		}
		AccountLog accountLog = new AccountLog();
		accountLog.setStartTime(new Date());
		accountLog.setId(UuidUtil.generateShortUuid());

		String bizType = "";
		TradeType recDepositeTradeType = null;
		TradeType recMangerTradeType = null;
		TradeType recRiskTradeType = null;
		String remark = "";
		String status = "";

		TradeParamsVO paramsVO = new TradeParamsVO();
		List<TradeDetailVO> detailsVO = new ArrayList<TradeDetailVO>();
		O2oLoanapplyAccountEntity loanapplyAccountEntity = io2oLoanapplyAccountService.getEntityByLoanapplyNo(expand.getLoanapply_no());
		if (null == loanapplyAccountEntity) {
			return "贷款单账户未开户，请联系运维同事";
		} else if (StringUtil.isBlank(loanapplyAccountEntity.getAccountNo())) {
			return "贷款单账户未开户，请稍后重试";
		}
		CustomerEntity getCustomerEntity = o2oChargeSituationService.getCustomerEntity(expand.getLoanapply_no());
		if (null == getCustomerEntity) {
			return "借款人个人账户未开户，请联系运维同事";
		}
		O2oLoanapplyEntity loanapplyEntity = o2oLoanapplyService.findById(expand.getLoanapply_no());
		TradeDetailVO recDeposite = new TradeDetailVO();// 封装保证金数据
		TradeDetailVO recManger = new TradeDetailVO();// 封装管理费数据
		TradeDetailVO recRisk = new TradeDetailVO();// 封装风险补偿金数据
		if (type.equals("KF")) {
			bizType = AccountConstants.ACCOUNT_KF;
			recDepositeTradeType = TradeType.DEPOSIT_IN;
			recMangerTradeType = TradeType.ISTRATION_IN;
			recRiskTradeType = TradeType.COMPENSATION_IN;
			remark = "扣费（交保证金管理费），单号：" + loanapplyEntity.getBillCode();
			status = StatusContexts.BZJ_STATUS_CLO;
			recDeposite.setAmount(expand.getRecDeposite());
			recDeposite.setRemark(remark);
			recManger.setAmount(expand.getRecManger());
			recManger.setRemark("交管理费，单号：" + loanapplyEntity.getBillCode());
			recRisk.setAmount(expand.getRecRisk());
			recRisk.setRemark("交风险补偿金，单号：" + loanapplyEntity.getBillCode());
			expandRecord.setStatus(StatusContexts.O2O_NO);
		} else if (type.equals("TF")) {
			bizType = AccountConstants.ACCOUNT_TF;
			recDepositeTradeType = TradeType.DEPOSIT_OUT;
			recMangerTradeType = TradeType.ISTRATION_OUT;
			recRiskTradeType = TradeType.COMPENSATION_OUT;
			remark = "退费（退保证金管理费），单号：" + loanapplyEntity.getBillCode();
			status = StatusContexts.BZJ_STATUS_NEW;
			recDeposite.setAmount(expand.getRedDeposite());
			recDeposite.setRemark(remark);
			recManger.setAmount(expand.getRedManger());
			recManger.setRemark("退管理费，单号：" + loanapplyEntity.getBillCode());
			recRisk.setAmount(expand.getRedRisk());
			recRisk.setRemark("退风险补偿金，单号：" + loanapplyEntity.getBillCode());
			// 更新临时表
			expandRecord.setStatus(StatusContexts.O2O_YES);
		}

		recDeposite.setRollInAccount(getCustomerEntity.getAccountId());// 转出账户
		recDeposite.setRollOutAccount(loanapplyAccountEntity.getAccountNo());// 转入账户
		recManger.setRollInAccount(getCustomerEntity.getAccountId());// 转出账户
		recManger.setRollOutAccount(loanapplyAccountEntity.getAccountNo());// 转入账户
		recRisk.setRollInAccount(getCustomerEntity.getAccountId());// 转出账户
		recRisk.setRollOutAccount(loanapplyAccountEntity.getAccountNo());// 转入账户

		recDeposite.setTradeType(recDepositeTradeType);
		recDeposite.setTradeBankcardNoIn("");// 本方交易银行卡号
		recDeposite.setTradeBankcardNoOut("");// 对方交易银行卡号
		recDeposite.setTradeDate(new Date());
		detailsVO.add(recDeposite);

		recManger.setTradeType(recMangerTradeType);
		recManger.setTradeBankcardNoIn("");// 本方交易银行卡号
		recManger.setTradeBankcardNoOut("");// 对方交易银行卡号
		recManger.setTradeDate(new Date());
		detailsVO.add(recManger);

		recRisk.setTradeType(recRiskTradeType);
		recRisk.setTradeBankcardNoIn("");// 本方交易银行卡号
		recRisk.setTradeBankcardNoOut("");// 对方交易银行卡号
		recRisk.setTradeDate(new Date());
		detailsVO.add(recRisk);

		paramsVO.setUniqueId(expandRecord.getId());
		paramsVO.setBizId(expandRecord.getId());// 业务ID取临时表ID，以便判断是否执行多次
		paramsVO.setBizType(bizType);
		paramsVO.setDetails(detailsVO);
		paramsVO.setRemark(remark);
		paramsVO.setRequestId(accountLog.getId());
		paramsVO.setSource(SourceType.WEB);

		ModelResult<String> result = null;
		String resultStr = "";
		try {
			logger.info("调用扣费接口开始，参数：【{}】", JSONObject.toJSONString(paramsVO));
			result = iFeeService.fee(paramsVO);
			logger.info("调用扣费接口结束，成功与否：{},【信息：{}】", result.isSuccess(), result.getErrMsg());
			if (result.isSuccess()) {// 如果调用成功
				if (type.equals("KF")) {
					// 插入临时表
					logger.info("调用临时表接口开始，参数：【{}】", JSONObject.toJSONString(expandRecord));
					int i = iO2oLoanapplyExpandRecordService.insert(expandRecord);
					logger.info("调用临时表接口结束，更新条数：【{}】", i);
				} else {
					logger.info("调用临时表接口开始，参数：【{}】", JSONObject.toJSONString(expandRecord));
					int i = iO2oLoanapplyExpandRecordService.update(expandRecord);
					logger.info("调用临时表接口结束，更新条数：【{}】", i);
				}
				o2oChargeSituationService.updateLoanapplyExpand(expand, status);//
				resultStr = "SUCCESS";
			} else {
				resultStr = result.getErrMsg();
			}
		} catch (Exception e) {
			logger.error("调用扣费接口失败，失败信息为：{}", e.getMessage());
			resultStr = "扣费失败";
		} finally {
			if (result.isSuccess()) {
				accountLog.setStatus(String.valueOf(result.isSuccess()));
			} else {
				accountLog.setStatus("false");
			}
			accountLog.setEndTime(new Date());
			accountLog.setRequestid(accountLog.getId());
			accountLog.setRequestPs(JSONObject.toJSONString(paramsVO));
			accountLog.setResponsePs(JSONObject.toJSONString(result));
			accountLog.setClassname(this.getClass().getName());
			accountLog.setLogType(AccountConstants.ACCOUNT_SF);
			accountLog.setLoanapplyNo(expand.getLoanapply_no());
			accountLog.setMethodname(Thread.currentThread().getStackTrace()[1].getMethodName());
			logger.info("调用service账号接口开始");
			iAccountLogService.add(accountLog);
			logger.info("调用service账号接口结束");
		}
		return resultStr;
	}
	/**
	 * 扣费、退费(运维直接扣费、退费)
	 * 
	 * @param expand
	 * @param type
	 * @return
	 */
	@Transactional(transactionManager = "o2oTransactionManager")
	public String ChargingKFTF(LoanapplyExpand expand, String type) {
		String uniqueId=UuidUtil.generateShortUuid();
		AccountLog accountLog = new AccountLog();
		accountLog.setStartTime(new Date());
		accountLog.setId(uniqueId);

		String bizType = "";
		TradeType recDepositeTradeType = null;
		TradeType recMangerTradeType = null;
		TradeType recRiskTradeType = null;
		String billcodesrc="单号："+expand.getBillCode()+"-";
		String remark = billcodesrc+"运维操作-"+type;
		String status = "";

		TradeParamsVO paramsVO = new TradeParamsVO();
		List<TradeDetailVO> detailsVO = new ArrayList<TradeDetailVO>();
		O2oLoanapplyAccountEntity loanapplyAccountEntity = io2oLoanapplyAccountService.getEntityByLoanapplyNo(expand.getLoanapply_no());
		if (null == loanapplyAccountEntity) {
			return "贷款单账户未开户，请联系运维同事";
		} else if (StringUtil.isBlank(loanapplyAccountEntity.getAccountNo())) {
			return "贷款单账户未开户，请稍后重试";
		}
		CustomerEntity getCustomerEntity = o2oChargeSituationService.getCustomerEntity(expand.getLoanapply_no());
		if (null == getCustomerEntity) {
			return "借款人个人账户未开户，请联系运维同事";
		}
		TradeDetailVO recDeposite = new TradeDetailVO();// 封装保证金数据
		TradeDetailVO recManger = new TradeDetailVO();// 封装管理费数据
		TradeDetailVO recRisk = new TradeDetailVO();// 封装风险补偿金数据
		if (type.equals("KF")) {
			bizType = AccountConstants.ACCOUNT_KF;
			recDepositeTradeType = TradeType.DEPOSIT_IN;
			recMangerTradeType = TradeType.ISTRATION_IN;
			recRiskTradeType = TradeType.COMPENSATION_IN;
			status = StatusContexts.BZJ_STATUS_CLO;
			recDeposite.setAmount(expand.getRecDeposite());
			recDeposite.setRemark(billcodesrc+"扣费（交保证金）-运维");
			recManger.setAmount(expand.getRecManger());
			recManger.setRemark(billcodesrc+"扣费（交管理费）-运维");
			recRisk.setAmount(expand.getRecRisk());
			recRisk.setRemark(billcodesrc+"扣费（交风险补偿金）-运维");
		} else if (type.equals("TF")) {
			bizType = AccountConstants.ACCOUNT_TF;
			recDepositeTradeType = TradeType.DEPOSIT_OUT;
			recMangerTradeType = TradeType.ISTRATION_OUT;
			recRiskTradeType = TradeType.COMPENSATION_OUT;
//			remark = "退费（退保证金管理费）-运维";
			status = StatusContexts.BZJ_STATUS_NEW;
			recDeposite.setAmount(expand.getRedDeposite());
			recManger.setAmount(expand.getRedManger());
			recRisk.setAmount(expand.getRedRisk());
			recDeposite.setRemark(billcodesrc+"退费（退保证金）-运维");
			recManger.setRemark(billcodesrc+"退费（退管理费）-运维");
			recRisk.setRemark(billcodesrc+"退费（退风险补偿金）-运维");
		}

		recDeposite.setRollInAccount(getCustomerEntity.getAccountId());// 转出账户
		recDeposite.setRollOutAccount(loanapplyAccountEntity.getAccountNo());// 转入账户
		recManger.setRollInAccount(getCustomerEntity.getAccountId());// 转出账户
		recManger.setRollOutAccount(loanapplyAccountEntity.getAccountNo());// 转入账户
		recRisk.setRollInAccount(getCustomerEntity.getAccountId());// 转出账户
		recRisk.setRollOutAccount(loanapplyAccountEntity.getAccountNo());// 转入账户

		recDeposite.setTradeType(recDepositeTradeType);
		recDeposite.setTradeBankcardNoIn("");// 本方交易银行卡号
		recDeposite.setTradeBankcardNoOut("");// 对方交易银行卡号
		recDeposite.setTradeDate(new Date());
		detailsVO.add(recDeposite);

		recManger.setTradeType(recMangerTradeType);
		recManger.setTradeBankcardNoIn("");// 本方交易银行卡号
		recManger.setTradeBankcardNoOut("");// 对方交易银行卡号
		recManger.setTradeDate(new Date());
		detailsVO.add(recManger);

		recRisk.setTradeType(recRiskTradeType);
		recRisk.setTradeBankcardNoIn("");// 本方交易银行卡号
		recRisk.setTradeBankcardNoOut("");// 对方交易银行卡号
		recRisk.setTradeDate(new Date());
		detailsVO.add(recRisk);

		paramsVO.setUniqueId(uniqueId);
		paramsVO.setBizId(uniqueId);// 业务ID取临时表ID，以便判断是否执行多次
		paramsVO.setBizType(bizType);
		paramsVO.setDetails(detailsVO);
		paramsVO.setRemark(remark);
		paramsVO.setRequestId(accountLog.getId());
		paramsVO.setSource(SourceType.WEB);

		ModelResult<String> result = null;
		String resultStr = "";
		try {
			logger.info("调用扣费接口开始，参数：【{}】", JSONObject.toJSONString(paramsVO));
			result = iFeeService.fee(paramsVO);
			logger.info("调用扣费接口结束，成功与否：{},【信息：{}】", result.isSuccess(), result.getErrMsg());
			if (result.isSuccess()) {// 如果调用成功
				o2oChargeSituationService.updateLoanapplyExpand(expand, status);//
				resultStr = "SUCCESS";
			} else {
				resultStr = result.getErrMsg();
			}
		} catch (Exception e) {
			logger.error("调用扣费接口失败，失败信息为：{}", e.getMessage());
			resultStr = "扣费失败";
		} finally {
			if (result.isSuccess()) {
				accountLog.setStatus(String.valueOf(result.isSuccess()));
			} else {
				accountLog.setStatus("false");
			}
			accountLog.setEndTime(new Date());
			accountLog.setRequestid(accountLog.getId());
			accountLog.setRequestPs(JSONObject.toJSONString(paramsVO));
			accountLog.setResponsePs(JSONObject.toJSONString(result));
			accountLog.setClassname(this.getClass().getName());
			accountLog.setLogType(AccountConstants.ACCOUNT_SF);
			accountLog.setLoanapplyNo(expand.getLoanapply_no());
			accountLog.setMethodname(Thread.currentThread().getStackTrace()[1].getMethodName());
			logger.info("调用service账号接口开始");
			iAccountLogService.add(accountLog);
			logger.info("调用service账号接口结束");
		}
		return resultStr;
	}
}
